import Vue from 'vue';
import router from '@/router/index';
import { getUserInfo } from '@/api/user';
import { passportUrl } from '@/api/common';

export default new Vue({
  data () {
    return {
      isInited: false, // 是否加载完成
      userInfo: null,
    };
  },

  computed: {
    isLogin () {
      return !!(this.userInfo?.id);
    },

    isAdmin () {
      return this.isLogin && this.userInfo?.role <= 2;
    },
  },

  methods: {
    async initLoginState (userInfo = null) {
      try {
        this.userInfo = userInfo || await getUserInfo();
        const { role, id } = this.userInfo;
        const isVisitAdmin = this.isVisitAdmin();
        if (id && role <= 2 && !isVisitAdmin) {
          router.replace('/admin');
        } else if ((!id || role > 2) && isVisitAdmin) {
          router.replace('/admin/login');
        } else if (role === 4 && this.isVisitPurchase()) {
          router.replace('/');
        }

        setTimeout(() => {
          this.isInited = true;
        });
      } catch (error) {

      } finally {
      }
    },

    async gotoLogin () {
      if (this.isVisitAdmin()) {
        router.push('/admin/login');
      } else {
        const url = await passportUrl();
        let returnUrl = `${document.location.protocol}//${document.location.host}`;
        if (router.currentRoute.meta?.loginReturnUrl) {
          returnUrl = `${document.location.protocol}//${document.location.host}${router.currentRoute.meta.loginReturnUrl}`;
        }
        location = url + encodeURIComponent(returnUrl);
      }
    },

    isVisitAdmin () {
      return location.pathname.indexOf('/admin') === 0;
    },

    isVisitPurchase () {
      return location.pathname.indexOf('/purchase') === 0;
    },
  },

});
